import React, { useState, useRef, useEffect } from 'react';
import { IoWaterOutline, IoSnowOutline, IoSunnyOutline } from 'react-icons/io5';
import { FiPower } from 'react-icons/fi';
import { 
  MdLightbulbOutline, 
  MdOutlineBathtub,
  MdPlayArrow,
  MdPause,
  MdSkipNext,
  MdSkipPrevious,
  MdSquare,
  MdVolumeUp,
  MdVolumeOff,
  MdArrowBack
} from 'react-icons/md';
import { 
  BsWindowDock,
  BsWindowStack
} from 'react-icons/bs';
import { useNavigate } from 'react-router-dom';
import styles from './smart.module.css'

const A = () => {
  const navigate = useNavigate();
  
  // 空调状态
  const [acPower, setAcPower] = useState(true);
  const [acMode, setAcMode] = useState('auto');
  const [targetTemp, setTargetTemp] = useState(25.6);

  // 灯光状态
  const [lights, setLights] = useState({
    main: true,
    hallway: true,
    bedroom: true,
    bathroom: true
  });

  // 窗帘状态
  const [curtains, setCurtains] = useState({
    living: false,
    bedroom: false
  });
  
  // 音乐播放状态
  const [isPlaying, setIsPlaying] = useState(false);
  const [isMuted, setIsMuted] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);
  const audioRef = useRef(null);
  
  // 使用不受CORS限制的公共音频文件或本地文件
  const songs = [
    {
      title: "风吹麦浪轻享版",
      // 使用相对路径的本地文件或CDN上不受CORS限制的音频
      src: "https://assets.codepen.io/4358584/Anitek_-_Komorebi.mp3"
    }
  ];
  
  const [currentSongIndex, setCurrentSongIndex] = useState(0);
  const [loading, setLoading] = useState(false);
  const [errorMsg, setErrorMsg] = useState("");
  
  // 音频加载状态更新
  useEffect(() => {
    const audio = audioRef.current;
    if (!audio) return;
    
    // 音频加载中
    const handleLoadStart = () => {
      setLoading(true);
      setErrorMsg("");
    };
    
    // 音频可以播放时
    const handleCanPlay = () => {
      setLoading(false);
    };
    
    // 音频加载出错时
    const handleError = (e) => {
      console.error("音频加载出错:", e);
      setLoading(false);
      setIsPlaying(false);
      setErrorMsg("音频加载失败，请稍后再试");
    };
    
    audio.addEventListener('loadstart', handleLoadStart);
    audio.addEventListener('canplay', handleCanPlay);
    audio.addEventListener('error', handleError);
    
    return () => {
      audio.removeEventListener('loadstart', handleLoadStart);
      audio.removeEventListener('canplay', handleCanPlay);
      audio.removeEventListener('error', handleError);
    };
  }, []);
  
  // 音频元数据和进度更新
  useEffect(() => {
    const audio = audioRef.current;
    if (!audio) return;
    
    const setAudioData = () => {
      setDuration(audio.duration);
      setLoading(false);
    };
    
    const setAudioTime = () => {
      setCurrentTime(audio.currentTime);
    };
    
    const onEnded = () => {
      setIsPlaying(false);
      if (currentSongIndex < songs.length - 1) {
        setTimeout(() => {
          setCurrentSongIndex(prevIndex => prevIndex + 1);
        }, 500);
      } else {
        setCurrentSongIndex(0);
      }
    };
    
    audio.addEventListener('loadedmetadata', setAudioData);
    audio.addEventListener('timeupdate', setAudioTime);
    audio.addEventListener('ended', onEnded);
    
    return () => {
      audio.removeEventListener('loadedmetadata', setAudioData);
      audio.removeEventListener('timeupdate', setAudioTime);
      audio.removeEventListener('ended', onEnded);
    };
  }, [currentSongIndex, songs.length]);
  
  // 当歌曲切换时重置状态
  useEffect(() => {
    setLoading(true);
    setErrorMsg("");
    
    if (isPlaying) {
      const playWhenReady = () => {
        const playPromise = audioRef.current.play();
        if (playPromise !== undefined) {
          playPromise
            .then(() => {
              setLoading(false);
            })
            .catch(error => {
              console.error("播放失败:", error);
              setIsPlaying(false);
              setLoading(false);
              setErrorMsg("播放失败，请点击播放按钮重试");
            });
        }
      };
      
      // 确保音频已加载后再尝试播放
      if (audioRef.current.readyState >= 2) {
        playWhenReady();
      } else {
        const canPlayHandler = () => {
          playWhenReady();
          audioRef.current.removeEventListener('canplay', canPlayHandler);
        };
        audioRef.current.addEventListener('canplay', canPlayHandler);
      }
    }
  }, [currentSongIndex, isPlaying]);
  
  // 播放/暂停切换
  const togglePlay = () => {
    if (errorMsg) setErrorMsg("");
    
    if (!isPlaying) {
      setLoading(true);
      const playPromise = audioRef.current.play();
      
      if (playPromise !== undefined) {
        playPromise
          .then(() => {
            setIsPlaying(true);
            setLoading(false);
          })
          .catch(error => {
            console.error("播放失败:", error);
            setIsPlaying(false);
            setLoading(false);
            setErrorMsg("播放失败，请再次点击尝试");
          });
      }
    } else {
      audioRef.current.pause();
      setIsPlaying(false);
    }
  };
  
  // 切换静音
  const toggleMute = () => {
    setIsMuted(!isMuted);
    if (audioRef.current) {
      audioRef.current.muted = !isMuted;
    }
  };
  
  // 下一首
  const nextSong = () => {
    setIsPlaying(false);
    setErrorMsg("");
    if (currentSongIndex < songs.length - 1) {
      setCurrentSongIndex(currentSongIndex + 1);
    } else {
      setCurrentSongIndex(0);
    }
  };
  
  // 上一首
  const prevSong = () => {
    setIsPlaying(false);
    setErrorMsg("");
    if (currentSongIndex > 0) {
      setCurrentSongIndex(currentSongIndex - 1);
    } else {
      setCurrentSongIndex(songs.length - 1);
    }
  };
  
  // 进度条更新
  const handleProgressChange = (e) => {
    const newTime = parseFloat(e.target.value);
    setCurrentTime(newTime);
    audioRef.current.currentTime = newTime;
  };
  
  // 格式化时间
  const formatTime = (time) => {
    if (isNaN(time)) return "0:00";
    
    const minutes = Math.floor(time / 60);
    const seconds = Math.floor(time % 60);
    return `${minutes}:${seconds < 10 ? '0' + seconds : seconds}`;
  };

  // 温度调整
  const adjustTemp = (amount) => {
    const newTemp = Number((targetTemp + amount).toFixed(1));
    if (newTemp >= 16 && newTemp <= 30) {
      setTargetTemp(newTemp);
    }
  };

  // 灯光控制
  const toggleLight = (light) => {
    setLights(prev => ({ ...prev, [light]: !prev[light] }));
  };

  // 窗帘控制
  const toggleCurtain = (room, state) => {
    setCurtains(prev => ({ ...prev, [room]: state }));
  };

  // 批量控制灯光
  const controlAllLights = (state) => {
    setLights(prev => {
      const newLights = { ...prev };
      Object.keys(newLights).forEach(key => {
        newLights[key] = state;
      });
      return newLights;
    });
  };

  // 批量控制窗帘
  const controlAllCurtains = (state) => {
    setCurtains(prev => {
      const newCurtains = { ...prev };
      Object.keys(newCurtains).forEach(key => {
        newCurtains[key] = state;
      });
      return newCurtains;
    });
  };

  return (
    <div className={styles.smartHomeContainer}>
      <audio 
        ref={audioRef} 
        src={songs[currentSongIndex].src} 
        preload="auto"
      />
      
      <div className={styles.headerBar} style={{background:'#34A9FE'}}>
        <button className={styles.backBtn} onClick={() => navigate(-1)}>
          <MdArrowBack size={24} />
        </button>
        <div className={styles.hotelFeature}>酒店智能</div>
        <div className={styles.controlsRight}>
          <span className={styles.dot}></span>
          <span className={`${styles.dot} ${styles.active}`}></span>
        </div>
      </div>

      <div className={styles.assistantSection}>
        <div className={styles.assistantAvatar}>
          <img src="https://www.logosc.cn/oss/icons/2022/09/20/PohtmoCJCiysZDR.png" alt="小杜管家" />
        </div>
        <div className={styles.assistantInfo}>
          <div className={styles.assistantName}>小杜管家</div>
          <div className={styles.assistantStatus}>有事叫"小杜"，我随时都在～</div>
        </div>
        <div className={styles.onlineStatus}>
          <span className={styles.statusDot}></span>
          <span>在线</span>
        </div>
      </div>

      <div className={styles.weatherStatsContainer}>
        <div className={styles.statItem}>
          <div className={styles.statValue}>26<span>℃</span></div>
          <div className={styles.statLabel}>温度</div>
        </div>
        <div className={styles.statItem}>
          <div className={styles.statValue}>62<span>%</span></div>
          <div className={styles.statLabel}>湿度</div>
        </div>
        <div className={styles.statItem}>
          <div className={styles.statValue}>37</div>
          <div className={styles.statLabel}>PM2.5</div>
        </div>
      </div>

      <div className={styles.musicPlayer}>
        <div className={styles.musicHeader}>
          <div className={styles.musicInfo}>{songs[currentSongIndex].title}</div>
          <button className={styles.muteBtn} onClick={toggleMute}>
            {isMuted ? <MdVolumeOff /> : <MdVolumeUp />}
          </button>
        </div>
        
        {errorMsg && <div className={styles.errorMessage}>{errorMsg}</div>}
        
        <div className={styles.musicProgress}>
          <span className={styles.timeCurrent}>{formatTime(currentTime)}</span>
          <input 
            type="range" 
            className={styles.progressBar}
            min="0"
            max={duration || 0}
            value={currentTime}
            onChange={handleProgressChange}
            step="0.01"
          />
          <span className={styles.timeTotal}>{formatTime(duration)}</span>
        </div>
        
        <div className={styles.playerControls}>
          <button className={styles.controlBtn} onClick={prevSong}>
            <MdSkipPrevious />
          </button>
          <button className={`${styles.controlBtn} ${styles.play}`} onClick={togglePlay} disabled={loading}>
            {loading ? (
              <span className={styles.loadingSpinner}></span>
            ) : isPlaying ? (
              <MdPause />
            ) : (
              <MdPlayArrow />
            )}
          </button>
          <button className={styles.controlBtn} onClick={nextSong}>
            <MdSkipNext />
          </button>
        </div>
      </div>

      <div className={styles.acControlSection}>
        <div className={styles.sectionHeader}>
          <div className={styles.sectionTitle}>中央空调</div>
          <button 
            className={`${styles.powerBtn} ${acPower ? styles.active : ''}`}
            onClick={() => setAcPower(!acPower)}
          >
            <FiPower />
          </button>
        </div>

        <div className={styles.tempControl}>
          <button 
            className={`${styles.tempBtn} ${styles.minus}`} 
            onClick={() => adjustTemp(-0.1)}
            disabled={!acPower}
          >-</button>
          <div className={styles.tempDisplay}>
            <div className={styles.tempValue}>目标温度{targetTemp}℃</div>
          </div>
          <button 
            className={`${styles.tempBtn} ${styles.plus}`} 
            onClick={() => adjustTemp(0.1)}
            disabled={!acPower}
          >+</button>
        </div>

        <div className={styles.modeSelector}>
          <button 
            className={`${styles.modeBtn} ${acMode === 'auto' ? styles.active : ''}`} 
            onClick={() => setAcMode('auto')}
            disabled={!acPower}
          >
            <div className={styles.modeIcon}>A</div>
            <span>自动</span>
          </button>
          <button 
            className={`${styles.modeBtn} ${acMode === 'cool' ? styles.active : ''}`} 
            onClick={() => setAcMode('cool')}
            disabled={!acPower}
          >
            <div className={styles.modeIcon}><IoSnowOutline /></div>
            <span>制冷</span>
          </button>
          <button 
            className={`${styles.modeBtn} ${acMode === 'heat' ? styles.active : ''}`} 
            onClick={() => setAcMode('heat')}
            disabled={!acPower}
          >
            <div className={styles.modeIcon}><IoSunnyOutline /></div>
            <span>制热</span>
          </button>
        </div>
      </div>

      <div className={styles.lightsSection}>
        <div className={styles.sectionHeader}>
          <div className={styles.sectionTitle}>全屋灯光</div>
          <div className={styles.lightActions}>
            <button onClick={() => controlAllLights(true)}>全开</button>
            <button onClick={() => controlAllLights(false)}>全关</button>
          </div>
        </div>

        <div className={styles.lightsGrid}>
          <div className={styles.lightControl}>
            <div className={styles.lightIcon}>
              <MdLightbulbOutline />
            </div>
            <div className={styles.lightName}>主灯</div>
            <label className={styles.switch}>
              <input 
                type="checkbox" 
                checked={lights.main}
                onChange={() => toggleLight('main')}
              />
              <span className={styles.slider}></span>
            </label>
          </div>

          <div className={styles.lightControl}>
            <div className={styles.lightIcon}>
              <MdLightbulbOutline />
            </div>
            <div className={styles.lightName}>廊灯</div>
            <label className={styles.switch}>
              <input 
                type="checkbox" 
                checked={lights.hallway}
                onChange={() => toggleLight('hallway')}
              />
              <span className={styles.slider}></span>
            </label>
          </div>

          <div className={styles.lightControl}>
            <div className={styles.lightIcon}>
              <MdLightbulbOutline />
            </div>
            <div className={styles.lightName}>床头灯</div>
            <label className={styles.switch}>
              <input 
                type="checkbox" 
                checked={lights.bedroom}
                onChange={() => toggleLight('bedroom')}
              />
              <span className={styles.slider}></span>
            </label>
          </div>

          <div className={styles.lightControl}>
            <div className={styles.lightIcon}>
              <MdOutlineBathtub />
            </div>
            <div className={styles.lightName}>浴室灯</div>
            <label className={styles.switch}>
              <input 
                type="checkbox" 
                checked={lights.bathroom}
                onChange={() => toggleLight('bathroom')}
              />
              <span className={styles.slider}></span>
            </label>
          </div>
        </div>
      </div>

      <div className={styles.curtainSection}>
        <div className={styles.sectionHeader}>
          <div className={styles.sectionTitle}>窗帘控制</div>
          <div className={styles.curtainActions}>
            <button onClick={() => controlAllCurtains(true)}>全开</button>
            <button onClick={() => controlAllCurtains(false)}>全关</button>
          </div>
        </div>

        <div className={styles.curtainsContainer}>
          <div className={styles.curtainCard}>
            <div className={styles.curtainHeader}>
              <div className={`${styles.curtainIcon} ${styles.living}`}>
                <BsWindowDock />
              </div>
              <div className={styles.curtainName}>客厅</div>
            </div>
            <div className={styles.curtainControls}>
              <button 
                className={`${styles.curtainBtn} ${styles.open}`}
                onClick={() => toggleCurtain('living', true)}
              >
                <BsWindowStack />
              </button>
              <button 
                className={styles.curtainBtn}
                onClick={() => controlAllCurtains(!Object.values(curtains).every(Boolean))}
              >
                <MdSquare />
              </button>
              <button 
                className={`${styles.curtainBtn} ${styles.close}`}
                onClick={() => toggleCurtain('living', false)}
              >
                <BsWindowDock />
              </button>
            </div>
          </div>

          <div className={styles.curtainCard}>
            <div className={styles.curtainHeader}>
              <div className={`${styles.curtainIcon} ${styles.bedroom}`}>
                <BsWindowDock />
              </div>
              <div className={styles.curtainName}>卧室</div>
            </div>
            <div className={styles.curtainControls}>
              <button 
                className={`${styles.curtainBtn} ${styles.open}`}
                onClick={() => toggleCurtain('bedroom', true)}
              >
                <BsWindowStack />
              </button>
              <button 
                className={styles.curtainBtn}
                onClick={() => toggleCurtain('bedroom', !curtains.bedroom)}
              >
                <MdSquare />
              </button>
              <button 
                className={`${styles.curtainBtn} ${styles.close}`}
                onClick={() => toggleCurtain('bedroom', false)}
              >
                <BsWindowDock />
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default A;